/*
 * Copyright (C) 2012, EADS France
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.frontends.functional;

/**
 *
 * @author Laurent WOUTERS
 */
public class OntologyLoader extends Loader {
    private xowl.lang.owl2.Ontology ontology;
    private xowl.interpreter.frontends.OntologyListener listener;

    public OntologyLoader(String input, xowl.interpreter.frontends.OntologyListener listener) {
        super(input);
        this.listener = listener;
    }

    @Override public xowl.lang.owl2.IRI getIRI(String fullIRI) { return listener.getIRI(fullIRI); }
    
    public xowl.lang.owl2.Ontology load(xowl.utils.logging.Logger logger, FElementNode node) throws FParserException {
        String iri = ((FIRINode)node.getChildren().get(0)).getIRI();
        ontology = listener.resolveOntology(listener.getIRI(iri));
        for (FNode child : node.getChildren()) {
            if (child.getType() != FNodeType.Element)
                continue;
            FElementNode elem = (FElementNode)child;
            try {
                if (xowl.interpreter.frontends.VocOWL2.ontoImport.equals(elem.getName())) {
                    // Treat import => Do nothing
                } else if (xowl.interpreter.frontends.VocOWL2.ontoAnnotation.equals(elem.getName())) {
                    // Treat annotation
                    ontology.addAnnotations(AnnotationLoader.load(this, elem, new xowl.interpreter.frontends.LexicalContext()));
                } else if (xowl.interpreter.frontends.VocRules.ruleRule.equals(elem.getName())) {
                    // Treat rule
                    xowl.lang.rules.Rule rule = RuleLoader.load(this, elem, new xowl.interpreter.frontends.LexicalContext());
                    if (rule != null)
                        listener.onRule(ontology, rule);
                } else {
                    // Treat as axiom
                    xowl.lang.owl2.Axiom axiom = AxiomLoader.load(this, elem, new xowl.interpreter.frontends.LexicalContext());
                    if (axiom != null)
                        listener.onAxiom(ontology, axiom);
                }
            } catch (java.lang.Exception ex) {
                logger.error(FunctionalLoader.name, "Functional Loader: Failed to load element at line " + elem.getLine(), ex);
            }
        }
        return ontology;
    }
}
